﻿using System;
using System.ComponentModel;
using System.IO;
using Cav;
using Cav.BaseClases;
using Nefela.CommonTypes;
using Novacode;

namespace Nefela.BusinessLogic
{
    public partial class DocumentBL : BusinessLogicBase
    {
        public DocumentBL()
        {
            InitializeComponent();
        }

        public DocumentBL(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }


        DocX wordDoc = null;

        public void OpenDocument(String FilePath)
        {
            if (!File.Exists(FilePath))
                throw new InvalidDataException("Неверно указан путь к файлу");

            wordDoc = DocX.Load(FilePath);
        }

        public void ReplaceText(String Pattern, String NewText)
        {
            if (Pattern.IsNullOrWhiteSpace())
                return;
            if (NewText.IsNullOrWhiteSpace())
                NewText = " ";
            wordDoc.ReplaceText(Pattern, NewText);
        }

        public void SaveDocumentAs(String FilePath)
        {
            wordDoc.SaveAs(FilePath);
        }

        internal void CloseDocument()
        {
            if (wordDoc != null)
                wordDoc.Dispose();

            wordDoc = null;
        }

        public void FillDocument(CustomerCardType CustomerCard, PackegeDocsType PackegeDocs)
        {
            var udir = Path.Combine(PackegeDocs.OutputDir, CustomerCard.Name.ReplaceInvalidPathChars() + " " + DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss "));
            if (!Directory.Exists(udir))
                Directory.CreateDirectory(udir);

            try
            {

                foreach (var doc in PackegeDocs.TemplatesDocs)
                {
                    string tempfile = Path.Combine(DomainContext.TempPath, Guid.NewGuid().ToString());
                    // сохраняем в темповый файл
                    File.WriteAllBytes(tempfile, doc.FileTemplate);

                    // открываем, заменяем текст
                    OpenDocument(tempfile);

                    foreach (var field in CustomerCard.Fields)
                        ReplaceText(field.FieldCardCustomer.LabelText, field.ReplacementText);

                    // сохраняем
                    string filename = doc.FileNameOutput + ".docx";
                    SaveDocumentAs(Path.Combine(udir, filename));

                }
            }
            catch
            {
                CloseDocument();
                throw;
            }
        }
    }
}
